const { Controller } = require('egg');
const AdmZip = require('adm-zip')
const fs = require('fs')
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    await ctx.render('gjz.html')
  }

  async upload() {
    const { ctx } = this

    const files = ctx.request.files
    if (files.length == 1 && ['application/x-zip-compressed', 'application/zip'].includes(files[0].mime)) {

      try {
        const zip = new AdmZip(files[0].filepath)
        fs.rmSync(`${ctx.app.baseDir}/dist`, {recursive: true})
        fs.mkdirSync(`${ctx.app.baseDir}/dist`)
        zip.extractAllTo(`${ctx.app.baseDir}/dist`, true)
        fs.renameSync(`${ctx.app.baseDir}/dist/${files[0].filename.split('.')[0]}`, `${ctx.app.baseDir}/dist/xuan`)
        
        ctx.body = {
          code: 200,
          msg: '单个的zip文件，解压完毕',
          data: {}
        }
      } catch (e) {
        ctx.body = {
          code: 400,
          msg: '解压时出现问题',
          data: e
        }
      }
    } else {
      try {
        fs.copyFileSync(files[0].filepath, `${ctx.app.baseDir}/dist/xuan/${files[0].filename}`)
        ctx.body = {
          code: 200,
          msg: '不是单个的zip文件，都复制过去了',
          data: {}
        }
      } catch (e) {
        ctx.body = {
          code: 200,
          msg: '复制文件失败',
          data: {}
        }
      }
    }    
  }
}

module.exports = HomeController;
